import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
  Spin
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.scss'
import { channels } from '@/api/article'
import { useEffect, useRef, useState } from 'react'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { addArticles, getArticleDetail, editArticles } from '@/api/article'
const { Option } = Select

const Publish = () => {
  const [loading, setLoading] = useState(true)
  const params = useParams()
  const navigate = useNavigate()
  // 备份图片
  const fileListRef = useRef([])
  const [fileList, setFileList] = useState([])
  // 富文本数据
  const [value] = useState('')
  // 获取频道数据
  const [channel, setChannel] = useState([])
  // 上传图片数量
  const [picCount, setPicCount] = useState(1)
  // 获取频道方法
  const getChannel = async () => {
    const { data } = await channels()
    setChannel(data.channels)
  }
  // 上传数量改变
  const changeType = (e) => {
    setPicCount(e.target.value)
    if (e.target.value === 1) {
      const img = fileListRef.current[0]
      setFileList(img ? [img] : [])
    } else if (e.target.value === 3) {
      setFileList(fileListRef.current)
    }
  }
  // 上传图片
  const onUploadChange = (info) => {
    // info.fileList 用来获取当前的文件列表
    const fileLists = info.fileList.map((file) => {
      // 刚从本地上传的图片
      console.log(file)
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      // 已有图片
      return file
    })
    setFileList(fileLists)
    fileListRef.current = fileLists
    console.log(fileLists)
  }
  // 发布文章方法提取
  const publishArticle = async ({ title, content, channel_id, type }, boo) => {
    if (type !== fileList.length) {
      return message.error('图片数量不一致')
    }
    const data = {
      title,
      content,
      channel_id,
      cover: {
        type,
        images: fileList.map((item) => item.url)
      }
    }
    // 判断是添加文章还是编辑文章
    if (params.id) {
      // 编辑文章
      await editArticles(data, boo, params.id)
      message.success('编辑成功')
    } else {
      // 发布文章
      await addArticles(data, boo)
      message.success('发布成功')
    }
    setFileList([])
    form.setFieldsValue({
      channel_id: null,
      type: null,
      content: '',
      title: ''
    })

    navigate('/layout/article')
  }
  // 发布文章
  const onSubmit = async (obj) => {
    await publishArticle(obj, false)
  }
  // form表单实例
  const [form] = Form.useForm()
  // 存入草稿
  const addDraft = async () => {
    try {
      const formData = await form.validateFields()
      await publishArticle(formData, true)
    } catch (err) {
      message.error('存入草稿失败')
    }
  }
  // 获取文章详情
  const getDetail = async () => {
    const {
      data: {
        channel_id,
        content,
        cover: { images, type },
        title
      }
    } = await getArticleDetail(params.id)
    const data = {
      channel_id,
      type,
      content,
      title
    }
    setFileList(images.map((item) => ({ url: item })))
    form.setFieldsValue(data)
    setLoading(false)
  }

  useEffect(() => {
    getChannel()
    if (params.id) {
      getDetail() // 获取文章详情
    } else {
      setLoading(false) // 关闭loading
    }
  }, [])
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {params.id ? '编辑文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Spin tip="努力加载中" spinning={loading}>
          <Form
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 1 }}
            onFinish={onSubmit}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                {channel.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="封面">
              <Form.Item name="type">
                <Radio.Group onChange={changeType}>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  <Radio value={0}>无图</Radio>
                  {/* <Radio value={-1}>自动</Radio> */}
                </Radio.Group>
              </Form.Item>
              {picCount !== 0 && (
                <Upload
                  maxCount={picCount}
                  className="avatar-uploader"
                  // 发到后台的文件参数名
                  // 必须指定，根据接口文档的说明，需要设置为 image
                  name="image"
                  // 上传组件展示方式
                  listType="picture-card"
                  // 展示已上传图片列表
                  showUploadList
                  // 接口地址
                  // 注意：Upload 再上传图片时，默认不会执行 axios 的请求，所以，此处需要手动设置完整接口地址
                  action="http://geek.itheima.net/v1_0/upload"
                  // 多选
                  multiple={picCount > 1}
                  // 已经上传的文件列表，设置该属性后组件变为 受控
                  fileList={fileList}
                  // 上传文件改变时的回调
                  onChange={onUploadChange}
                >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
              <ReactQuill theme="snow" value={value} />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  发布文章
                </Button>
                <Button size="large" onClick={addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    </div>
  )
}

export default Publish
